import axios from 'axios'
import type { AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { TOKEN_KEY } from "@/enums/CacheEnum"
import { ElMessage, ElMessageBox } from 'element-plus';

interface pendingTask {
  config: AxiosRequestConfig,
  resolve: Function
}

let refreshing = false
const quoue: pendingTask[] = [];

function dataType(data: any) {
  return Object.prototype.toString
    .call(data)
    .slice(8, -1)
    .toLowerCase();
}

//创建axios 实例

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 100000, //请求超时时间
  transformRequest: [
    data => {
      if (dataType(data) === "formdata") {
        return data;
      }
      data = JSON.stringify(data);
      return data;
    }
  ],
  headers: {
    get: {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    },
    post: {
      "Content-Type": "application/json;charset=utf-8"
    }
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem(TOKEN_KEY);
    if (token) {
      config.headers.Authorization = token;
    }
    // 不去空参数
    let whiteArrUrl: string[] = [];
    if (config.url && whiteArrUrl.includes(config.url)) {
      for (let key in config.data) {
        if (
          !config.data[key] &&
          config.data[key] !== 0 &&
          config.data[key] !== false
        )
          config.data[key] = "";
        // 连续空格串处理
        if (
          typeof config.data[key] === "string" &&
          config.data[key].trim() === ""
        )
          config.data[key] = "";
      }
    } else {
      // 参数去空
      for (let key in config.data) {
        if (
          !config.data[key] &&
          config.data[key] !== 0 &&
          config.data[key] !== false
        )
          delete config.data[key];
      }
    }


    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

//响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message } = response.data
    if (code === 0) {
      return response.data
    }
    if (response.data instanceof ArrayBuffer) {
      return response
    }
    ElMessage.error(message || "系统出错");
    return Promise.reject(new Error(message || "Error"))
  },
  (error: any) => {
    console.log(error, 'response.error')
    let { data, config } = error.response
    if (refreshing) {
      return new Promise((resolve, reject) => {
        quoue.push({ config, resolve })
      })
    }
    if (error.response.data) {
      refreshing = false
      const { code, message } = error.response.data
      if (error.response.status === 401) {
        //   ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
        //     confirmButtonText: "确定",
        //     type: "warning",
        //   }).then(() => {
        //     localStorage.clear();
        //     window.location.href = "/";
        //   });
      }
      if (error.response.status === 403) {
        //拿refresh_token刷新token
        refreshing = true
        quoue.forEach(({ config, resolve }) => {
          resolve(service(config))
        })
        ElMessage.error(message || "系统出错");
        return service(config)
      }
      ElMessage.error(message || "系统出错");
    }
    return Promise.reject(error.message);
  }
)

// 导出 axios 实例
export default service;